package com.ruoyi.framework.config;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @ClassTitle: ValidationExceptionConfig
 * @ProjectName pricingboot
 * @Description: 自定义ExceptionHandler拦截校验异常
 * @Author Hush. ultraman_zero@aliyun.com
 * @Date 2021/5/12
 * @Time 15:06
 */
@ControllerAdvice
public class ValidationConfig extends ResponseEntityExceptionHandler {


    private final Logger logger = LoggerFactory.getLogger(getClass());

    @ExceptionHandler({ConstraintViolationException.class})
    @ResponseBody
    public AjaxResult handleConstraintViolation(ConstraintViolationException e) {

        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        Set<String> messages = new HashSet<>(constraintViolations.size());
        messages.addAll(constraintViolations.stream()
                .map(violation -> {
                            logger.error(String.format("%s ( '%s' )： %s",
                                    violation.getPropertyPath().toString(),
                                    violation.getInvalidValue(),
                                    violation.getMessage()));
                            return violation.getMessage();
                        }
                )
                .collect(Collectors.toList()));
        return AjaxResult.error(StringUtils.join(messages, "、"));
    }

}

